//
//  SIComposeViewController.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/9.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit
import SVProgressHUD

class SIComposeViewController: UIViewController {
    
    /// 文本视图
    @IBOutlet weak var textView: SIComposeTextView!

    /// 底部工具栏
    @IBOutlet weak var toolBar: UIToolbar!
    
    
    /// 发布微博按钮
    @IBOutlet var sendButton: UIButton!
    
    /// 标题
    @IBOutlet var titleLabel: UILabel!
    
    /// 底部工具栏底部约束
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    
    lazy var emoticonView: SIEmoticonInputView = SIEmoticonInputView.inputView { [weak self] (emoticon) in
        
        self?.textView.insertEmoticon(em: emoticon)
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.purple()
        
        setupUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //激活键盘
        textView.becomeFirstResponder()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        textView.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //关闭键盘
        textView.resignFirstResponder()
    }
    
    //MARK: -键盘监听方法
    @objc private func keyboardChanged(n: NSNotification) {
        
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue(),
            duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else {
                return
        }
        
        let offset = view.bounds.height - rect.origin.y
        
        toolBarBottomCons.constant = offset
        
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
    let cell = UITableViewCell()
    
    

    //MARK: 按钮监听方法
    ///发布微博
    @IBAction func sendNewInformation(_ sender: AnyObject) {
        
        print("发布微博")
//        
//        guard let text = textView.text else {
//            
//            return
//            
//        }
        let text = textView.emoticonText
        // FIXME: -临时测试
        let image: UIImage? = nil
        
        SINetworkTools.shared.postStatus(text: text, image: image) { (result, isSuccess) in
//            print(result)
            // MARK: -发布完成
            SVProgressHUD.setDefaultStyle(.dark)
            
            let message = isSuccess ? "发布成功" : "网络不给力"
            
            SVProgressHUD.showInfo(withStatus: message)
            
            if isSuccess {
                
                DispatchQueue.main.after(when: DispatchTime.now() + 1, execute: { 
                    SVProgressHUD.setDefaultStyle(.light)
                    
                    self.dismissComposeView()
                })
                
            }
        }
        
    }
   
    // MARK: - 关闭发布界面
    @objc private func dismissComposeView() {
        
        dismiss(animated: true, completion: nil)
    }
    
    ///切换表情键盘
    @objc private func emoticonKeyboard() {
        
        let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 253))
        
        keyboardView.backgroundColor = UIColor.blue()
        
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        
        textView.reloadInputViews()
        
    }

}

// MARK: - UITextViewDelegate
extension SIComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        
        sendButton.isEnabled = textView.hasText()
    }
    
}

extension SIComposeViewController {
    
    ///设置界面
    func setupUI() {
        
        view.backgroundColor = UIColor.white()
        
        setupNavigationBar()
        
        setupToolbar()
        
    }
    
    /// 设置工具栏
    func setupToolbar() {
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        for s in itemSettings {
            
            guard let imageName = s["imageName"] else {
                
                continue
                
            }
            
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            
            let btn = UIButton()
            
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            
            if let actionName = s["actionName"] {
                btn.addTarget(self
                    , action: Selector(actionName), for: .touchUpInside)
            }
            
            items.append(UIBarButtonItem(customView: btn))
            
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil
                ))
        }
        
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    /// 建立导航栏
    func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: #selector(dismissComposeView))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        navigationItem.titleView = titleLabel
        
        sendButton.isEnabled = false
    }
    
}
